package com.weixin.base.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.weixin.entity.message.ResTextMessage;

public class Tools {

	public final static String tpMainName = "首页";
	public final static String tpMainText = "文章";
	public final static String[] colors={"blue","aqua","black","fuchsia","gray","green","lime","maroon","navy","olive","purple","red","silver","teal"};

	public Tools() {

	}

	/**
	 * 随机码=类型+日期（精确到毫秒）+3位随机数
	 * 
	 * @return 类型1.文章随机码- 2.微信回复图片3首页菜单图片
	 */
	public static String radomName(int type) {
		SimpleDateFormat dataformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");

		Random rdm = new Random();
		int rd = rdm.nextInt(10);
		int rd2 = rdm.nextInt(10);
		int rd3 = rdm.nextInt(10);

		return type + dataformat.format(new Date()) + rd + rd2 + rd3;
	}

	public static boolean upload(String strNewFileName, InputStream is, String folderPath) throws Exception {
		boolean flg = false;
		newFolder(folderPath);
		try {
			writetotxt(folderPath + strNewFileName, is);
			flg = true;
		} catch (Exception e) {
			e.printStackTrace();
			// throw e;
		} finally {
			if (is != null) {
				is.close();
			}
		}
		return flg;
	}

	/**
	 * 创建文件夹
	 */
	public static void newFolder(String folderPath) {

		File myFilePath = new File(folderPath.toString());
		if (!myFilePath.isDirectory()) {
			myFilePath.mkdirs();
		}
	}

	/**
	 * 创建文件
	 */
	public static File creatTxtFile(String filenameTemp) {

		File file = new File(filenameTemp);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	/**
	 * 写入
	 */
	public static void writetotxt(String folderPath, InputStream is) throws IOException {
		FileOutputStream fos = null;

		try {
			File file = creatTxtFile(folderPath.toString());
			fos = new FileOutputStream(file);
			// 从源文件中取数据，写到目标文件中
			byte[] buff = new byte[8192];
			for (int len = -1; (len = is.read(buff)) != -1;) {
				fos.write(buff, 0, len);
			}
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}

	/**
	 * 验证签名
	 * 
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String signature, String timestamp, String nonce, String token) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;

		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}

	public static String EncoderByMd5(String sou) {
		if (sou == null || sou.equals("")) {
			return "";
		}
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = sou.getBytes();
			// 使用MD5创建MessageDigest对象
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte b = md[i];
				// System.out.println((int)b);
				// 将没个数(int)b进行双字节加密
				str[k++] = hexDigits[b >> 4 & 0xf];
				str[k++] = hexDigits[b & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * UCS2编码
	 * 
	 * @param sData
	 *            UTF-16BE编码的源串
	 * @return 编码后的UCS2串
	 */
	public static String encodeUCS2(String sData) {
		byte[] aBytes = null;
		StringBuffer sReValue = new StringBuffer();

		try {
			aBytes = sData.getBytes("UTF-16BE");
			for (int i = 0, nLen = aBytes.length; i < nLen; i++) {
				StringBuffer sBuffer = new StringBuffer();
				sBuffer.append(Integer.toHexString(aBytes[i] & 0xFF));
				if (sBuffer.length() == 1) {
					sBuffer.insert(0, '0');
				}
				sReValue.append(sBuffer);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sReValue.toString().toLowerCase();
	}

	public static String HZtoEncode(String sData) {
		String sRet = "";
		List<String> list = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		sRet = Tools.encodeUCS2(sData);
		if ((sRet.length()) % 4 == 0) {
			int n = (sRet.length()) / 4;
			for (int i = 0; i < n; i++) {
				// System.out.println(sRet.substring(i*4, (i*4)+4));
				list.add(sRet.substring(i * 4, (i * 4) + 4));
			}
			int k = list.size();
			for (int j = 0; j < k; j++) {
				String str = list.get(j);
				sb.append("\\x").append(str.substring(2)).append("\\x").append(str.substring(0, 2));
			}
			sb.append("\\x00\\x00");
		}
		// System.out.println(sb.toString());
		return sb.toString();
	}

	public static String convertRs(Object obj) {
		return obj == null ? "" : obj.toString();
	}

	public static int convertRi(Object obj) {
		if (obj == null) {
			return 0;
		}
		return obj.equals("") ? 0 : Integer.parseInt(obj.toString());
	}

	public static double convertRd(Object obj) {
		if (obj == null) {
			return 0;
		}
		return obj.equals("") ? 0 : Double.parseDouble(obj.toString());
	}

	public static float convertRf(Object obj) {
		if (obj == null) {
			return 0;
		}
		return obj.equals("") ? 0 : Float.parseFloat(obj.toString());
	}

	/**
	 * 计算采用utf-8编码方式时字符串所占字节数
	 * 
	 * @param content
	 * @return
	 */
	public static int getByteSize(String content) {
		int size = 0;
		if (null != content) {
			try {
				// 汉字采用utf-8编码时占3个字节
				size = content.getBytes("utf-8").length;
				// size = content.getBytes("gb2312").length;
				// size = content.getBytes("GBK").length;
				// size = content.getBytes("ISO8859-1").length;
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return size;
	}
	
	public static String getColors(){
		
		Random rdm = new Random();
		int rd = rdm.nextInt(colors.length);
		return colors[rd];
	}

	public static void main(String[] args) {
		
		for (int i = 0; i < 1000; i++) {
			System.out.println(getColors());
		}
		
//		boolean ff = Tools.checkSignature("50846b08f9e6ab7f13a907ae39f5b89d9ec57486", "1385959720", "1386191140", "ceshitoken");
//		ResTextMessage resTextMessage = new ResTextMessage();
//		resTextMessage.setToUserName("aaa");
//		resTextMessage.setFromUserName("bbb");
//		resTextMessage.setCreateTime(new Date().getTime());
//		resTextMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
//		resTextMessage.setContent("yyy");
//		String aa = MessageUtil.textMessageToXml(resTextMessage);
//		System.out.println(aa);
		// String str = "user1";
		// int n = Integer.parseInt("30", 16);
		// Tools.decode7bit(str,n);
		// System.out.println(Tools.EncoderByMd5(str));
		// System.out.println(ff);
	}
}
